package com.example.feifei.newproject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.support.v4.util.LruCache;
import android.support.v4.widget.DrawerLayout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.disklrucache.DiskLruCache;
import com.example.feifei.utils.LogUtils;
import com.example.feifei.view.popwindow.WheelPopupwidnow;
import com.example.feifei.view.popwindow.WheelView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.EncodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.itheima.wheelpicker.WheelPicker;

import org.apache.http.util.EncodingUtils;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import static com.example.feifei.newproject.R.drawable.ic_star_rate_on;

/**
 * Created by feifei on 2017/7/13.
 */

public class ChatDemoActivity extends Activity implements View.OnClickListener {

    private DrawerLayout drawer_layout;
    private Button show_menu;
    private LinearLayout layout_content;
    private WheelPicker view_wheelPicker;

    private Button btn_selectWindow;
    private Button btn_bottom_dialog;
    private Button app_test;
    private Button btn_createQR;
    private ImageView newImageQR;
    private int getI;

    private List<String> listString;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int mCurrentOrientation = getResources().getConfiguration().orientation;
        //竖屏
        if (mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            LogUtils.e("现在是竖屏");
            setContentView(R.layout.activity_chatdemo);
            drawer_layout = (DrawerLayout) this.findViewById(R.id.drawer_layout);
            //侧滑菜单组件
            show_menu = (Button) this.findViewById(R.id.show_menu);
            show_menu.setOnClickListener(this);
            //底部弹出框
            btn_bottom_dialog = (Button) this.findViewById(R.id.btn_bottom_dialog);
            btn_bottom_dialog.setOnClickListener(this);
            //应用测试跳转
            app_test = (Button) this.findViewById(R.id.app_test);
            app_test.setOnClickListener(this);
            //单选框测试
            btn_selectWindow = (Button) this.findViewById(R.id.btn_selectWindow);
            btn_selectWindow.setOnClickListener(this);
            //二维码设置
            initQRCard();
            //获取数据
            listString = getStringList();
        //横屏
        } else if (mCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            LogUtils.e("现在是横屏");
            setContentView(R.layout.activity_cahtdemo_land);
            listString = (List<String>) getLastNonConfigurationInstance();
            if(null != listString){
                LogUtils.e("得到数据=="+listString.toString().trim());
            }else{
                LogUtils.e("得到数据为空==");
            }
        }
    }


    //横竖屏切换记录
    @Override
    public Object onRetainNonConfigurationInstance() {
        final List<String> list = listString;
        return list;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击弹出popupwindow
            case R.id.show_menu:
                List<String> listData = getStringList();
                WheelPopupwidnow wheelWindow = new WheelPopupwidnow(this, listData);
                wheelWindow.showPopupWindow(drawer_layout);
                wheelWindow.setonCommitClickListener(new WheelPopupwidnow.OnCommitClickListener() {

                    @Override
                    public void OnCommitClick(String listItem) {
                        // TODO Auto-generated method stub
                        Toast.makeText(ChatDemoActivity.this, listItem, Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            //底部弹出框
            case R.id.btn_bottom_dialog:
                showBottomDialog();
                break;
            //跳转app展示
            case R.id.app_test:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("http://app.mi.com/details?id=com.clubbear.paile&ref=search"));
                startActivity(intent);
                break;
            //单选框展示
            case R.id.btn_selectWindow:
                initSelectWindow();
                break;
            //生成二维码图片
            case R.id.btn_createQR:
                newImageQR.setImageBitmap(createQRCode("长按识别", 500));
                break;
        }
    }

    //模拟list数据
    private List<String> getStringList() {
        List<String> listString = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            listString.add("北京" + i);
        }
        return listString;
    }

    //弹出底部测试框
    private void showBottomDialog() {
        Dialog dialog = new Dialog(this, R.style.Theme_Light_Dialog);
        View citydialog = LayoutInflater.from(this).inflate(R.layout.dialog_test_view, null);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.AnimBottom);
        //设置为底部全屏，无间距
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); // 获取对话框当前的参数值
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);

        dialog.show();
        dialog.setContentView(citydialog);
    }

    //二维码设置
    private void initQRCard() {
        //二维码生成
        btn_createQR = (Button) this.findViewById(R.id.btn_createQR);
        btn_createQR.setOnClickListener(this);
        newImageQR = (ImageView) this.findViewById(R.id.newImageQR);
        newImageQR.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Bitmap obmp = ((BitmapDrawable) (newImageQR).getDrawable()).getBitmap();
                int width = obmp.getWidth();
                int height = obmp.getHeight();
                int[] data = new int[width * height];
                obmp.getPixels(data, 0, width, 0, 0, width, height);
                RGBLuminanceSource source = new RGBLuminanceSource(width, height, data);
                BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
                QRCodeReader reader = new QRCodeReader();
                Result re = null;
                try {
                    re = reader.decode(bitmap1);
                } catch (NotFoundException e) {
                    e.printStackTrace();
                } catch (ChecksumException e) {
                    e.printStackTrace();
                } catch (FormatException e) {
                    e.printStackTrace();
                }
                if (re != null) {
                    Toast.makeText(ChatDemoActivity.this, re.getText(), Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });
    }

    //生成二维码
    private Bitmap createQRCode(String text, int size) {
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, hints);
            int[] pixels = new int[size * size];
            for (int y = 0; y < size; y++) {
                for (int x = 0; x < size; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * size + x] = 0xff000000;
                    } else {
                        pixels[y * size + x] = 0xffffffff;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
            return addLogo(bitmap,BitmapFactory.decodeResource(getResources(),R.drawable.ic_star_rate_on));
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加 Logo
     * @param qrBitmap  二维码图片
     * @param logoBitmap   logo图片
     * @return
     */
    private Bitmap addLogo(Bitmap qrBitmap, Bitmap logoBitmap) {
        int qrBitmapWidth = qrBitmap.getWidth();
        int qrBitmapHeight = qrBitmap.getHeight();
        int logoBitmapWidth = logoBitmap.getWidth();
        int logoBitmapHeight = logoBitmap.getHeight();
        Bitmap blankBitmap = Bitmap.createBitmap(qrBitmapWidth, qrBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(blankBitmap);
        canvas.drawBitmap(qrBitmap, 0, 0, null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        float scaleSize = 1.0f;
        while ((logoBitmapWidth / scaleSize) > (qrBitmapWidth / 5) || (logoBitmapHeight / scaleSize) > (qrBitmapHeight / 5)) {
            scaleSize *= 2;
        }
        float sx = 1.0f / scaleSize;
        canvas.scale(sx, sx, qrBitmapWidth / 2, qrBitmapHeight / 2);
        canvas.drawBitmap(logoBitmap, (qrBitmapWidth - logoBitmapWidth) / 2, (qrBitmapHeight - logoBitmapHeight) / 2, null);
        canvas.restore();
        return blankBitmap;
    }

    //单选框
    private void initSelectWindow() {
        final Dialog dialog = new Dialog(this, R.style.Theme_Light_Dialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_wheel_view, null);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.AnimBottom);
        //设置为底部全屏，无间距
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); // 获取对话框当前的参数值
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
        //开始内容设置
        TextView selectWheelCancle = (TextView) view.findViewById(R.id.selectWheelCancle);
        TextView selectWheelSure = (TextView) view.findViewById(R.id.selectWheelSure);
        //取消按钮
        selectWheelCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        selectWheelSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ChatDemoActivity.this, getStringList().get(getI), Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        WheelPicker picker = (WheelPicker) view.findViewById(R.id.view_wheelPicker);
        List<String> contentList = getStringList();
        picker.setData(contentList);
        picker.setOnItemSelectedListener(new WheelPicker.OnItemSelectedListener() {
            @Override
            public void onItemSelected(WheelPicker wheelPicker, Object o, int i) {
                //getI必须为全局，否则不能显示
                getI = i;
            }
        });

        dialog.show();
        dialog.setContentView(view);
    }


}
